package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"short-vid-hub/cache"
	"short-vid-hub/model"
	"strconv"
	"time"
)

func CarAdd(c *gin.Context) {
	name := c.PostForm("name")
	address := c.PostForm("address")
	price := c.PostForm("price")
	data := model.Car{
		Name:    name,
		Address: address,
		Price:   price,
	}
	model.DB.Create(&data).Debug()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
	})
	return
}
func OrderAdd(c *gin.Context) {
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	order_price := c.PostForm("order_price")
	order_time := c.PostForm("order_time")
	data := model.Order{
		Cid:        cid,
		OrderPrice: order_price,
		OrderTime:  order_time,
	}
	model.DB.Create(&data).Debug()
	c.JSON(200, gin.H{
		"msg":  200,
		"data": "ok",
	})
	return
}
func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	redis_key := "car_order_list" + strconv.Itoa(page)
	var order []model.CarOrder
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").Select(
			"cars.name as Name",
			"cars.address as Address",
			"cars.price as Price",
			"orders.cid as Cid",
			"orders.order_price as OrderPrice",
			"orders.order_time as OrderTime",
		).Joins("LEFT JOIN cars ON orders.cid=cars.id").
			Offset(offset).Limit(size).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	var total int64
	model.DB.Model(&model.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "OK",
		"data":  order,
		"total": total,
	})
}
func CarOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var order model.CarOrder
	redis_key := "car_order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").Select(
			"cars.name as Name",
			"cars.address as Address",
			"cars.price as Price",
			"orders.cid as Cid",
			"orders.order_price as OrderPrice",
			"orders.order_time as OrderTime",
		).Joins("LEFT JOIN cars ON orders.cid=cars.id").
			Where("orders.id=?", id).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	var total int64
	model.DB.Model(&model.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "OK",
		"data":  order,
		"total": total,
	})
}
